package cn.dengta.webapp.trade.entity.meta;

import java.util.Date;

import cn.dengta.context.model.Language;
import cn.dengta.webapp.base.entity.BizEntity;
import cn.dengta.webapp.trade.model.MetaConfigType;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import me.codeplayer.util.StringUtil;
import me.codeplayer.util.X;

/**
 * 元数据资料配置表
 *
 * @author lgy
 * @since 2022-03-26
 */
@Setter
@Getter
@Accessors(chain = true)
@TableName("dt_meta_config")
public class MetaConfig extends BizEntity {

	/** 语言 */
	private Language language;
	/** 用户ID */
	private Long userId;
	/** 最后更新人 */
	public Long lastOperator;
	/** 名称 */
	private String name;
	/** 图片 */
	private String image;
	/** 摘要 */
	private String summary;
	/** 标签 */
	private String tag;
	/** 业务类型 */
	private MetaConfigType type;
	/** 规则JSON配置 */
	private String config;
	/** 备注信息 */
	private String remark;
	/** 次数 */
	private Integer useNum;

	/** 已解析到的配置对象 */
	protected transient MetaRuleConfig resolvedCfg;

	public MetaConfig init(MetaConfig input, Date now) {
		this.language = X.expectNotNull(language, input.language);
		this.userId = X.expectNotNull(userId, input.userId);
		this.image = X.expectNotEmpty(input.image, image);
		this.name = X.expectNotNull(input.name, name);
		this.summary = X.expectNotNull(input.summary, summary);
		this.tag = X.expectNotNull(input.tag, tag);
		this.type = X.expectNotNull(type, input.type);
		this.remark = StringUtil.toString(input.remark);
		this.config = StringUtil.toString(input.config);
		if (input.getType() == MetaConfigType.USER_RECHARGE_LIMIT){
			this.useNum = input.useNum;
		}
		super.initTime(now);
		super.init(input.status, input.state);
		return this;
	}

	@Override
	public void setId(Long id) {
		this.id = id;
	}

	public <T extends MetaRuleConfig> T getResolvedCfg() {
		MetaRuleConfig cfg = resolvedCfg;
		if (cfg == null) {
			resolvedCfg = cfg = type.deserialize(config);
		}
		return X.castType(cfg);
	}

	public void updateCfg(MetaRuleConfig config) {
		this.config = type.serialize(this.resolvedCfg = config);
	}

	public <T extends MetaRuleConfig> T updateResolvedCfg(String config) {
		this.resolvedCfg = type.deserialize(this.config = config);
		return getResolvedCfg();
	}

	/**
	 * 配置接口
	 */
	public interface MetaRuleConfig extends java.io.Serializable {

		void validate();

		void init(MetaRuleConfig config);

	}

	public static final String TYPE = "type";
	public static final String NAME = "name";
	public static final String LANGUAGE = "language";
	public static final String USER_ID = "user_id";
	public static final String IMAGE = "image";
	public static final String SUMMARY = "summary";
	public static final String TAG = "tag";
	public static final String CONFIG = "config";
	public static final String REMARK = "remark";

}
